package org.nobody.mallb2c.mallproduct.service.impl;

import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang.StringUtils;
import org.nobody.common.utils.R;
import org.nobody.mallb2c.mallproduct.entity.SkuImagesEntity;
import org.nobody.mallb2c.mallproduct.entity.SpuInfoDescEntity;
import org.nobody.mallb2c.mallproduct.feign.SeckillFeignService;
import org.nobody.mallb2c.mallproduct.service.*;
import org.nobody.mallb2c.mallproduct.vo.SeckillInfoVo;
import org.nobody.mallb2c.mallproduct.vo.SkuItemSaleAttrVo;
import org.nobody.mallb2c.mallproduct.vo.SkuItemVo;
import org.nobody.mallb2c.mallproduct.vo.SpuItemAttrGroupVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.nobody.common.utils.PageUtils;
import org.nobody.common.utils.Query;

import org.nobody.mallb2c.mallproduct.dao.SkuInfoDao;
import org.nobody.mallb2c.mallproduct.entity.SkuInfoEntity;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

  @Autowired
  SkuImagesService skuImagesService;

  @Autowired
  SpuInfoDescService spuInfoDescService;

  @Autowired
  AttrGroupService attrGroupService;

  @Autowired
  SkuSaleAttrValueService skuSaleAttrValueService;

  @Autowired
  ThreadPoolExecutor executor;

  @Autowired
  SeckillFeignService seckillFeignService;

  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    IPage<SkuInfoEntity> page = this.page(
      new Query<SkuInfoEntity>().getPage(params),
      new QueryWrapper<SkuInfoEntity>()
    );

    return new PageUtils(page);
  }

  @Override
  public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
    this.baseMapper.insert(skuInfoEntity);
  }

  @Override
  public PageUtils queryPageByCondition(Map<String, Object> params) {
    QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<SkuInfoEntity>();

    String key = (String) params.get("key");
    if (!StringUtils.isEmpty(key)) {
      wrapper.and((w) -> {
        w.eq("sku_id", key).or().like("sku_name", key);
      });
    }

    String catalogId = (String) params.get("catalogId");
    if (!StringUtils.isEmpty(catalogId) && !"0".equalsIgnoreCase(catalogId)) {
      wrapper.eq("catalog_id", catalogId);
    }

    String brandId = (String) params.get("brandId");
    if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
      wrapper.eq("brand_id", brandId);
    }

    String min = (String) params.get("min");
    if (!StringUtils.isEmpty(min)) {
      wrapper.ge("price", min);
    }

    String max = (String) params.get("max");
    if (!StringUtils.isEmpty(max)) {
      try {
        BigDecimal bigDecimal = new BigDecimal(max);
        if (bigDecimal.compareTo(new BigDecimal("0")) == 1) wrapper.le("price", max);
      } catch (Exception e) {
      }
    }


    IPage<SkuInfoEntity> page = this.page(
      new Query<SkuInfoEntity>().getPage(params),
      wrapper
    );

    return new PageUtils(page);
  }

  @Override
  public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
    return this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
  }

  @Override
  public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
    SkuItemVo skuItemVo = new SkuItemVo();

    CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
      //1、sku基本信息获取 pms_sku_info
      SkuInfoEntity info = getById(skuId);
      skuItemVo.setInfo(info);

      return info;
    }, executor);

    //下面三是并行的
    CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync(res -> {
      //3、获取spu的销售属性组合
      List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
      skuItemVo.setSaleAttr(saleAttrVos);
    }, executor);
    CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync(res -> {
      //4、获取spu的介绍
      SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
      skuItemVo.setDesp(spuInfoDescEntity);
    }, executor);
    CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync(res -> {
      //5、获取spu的规格参数
      List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
      skuItemVo.setGroupAttrs(attrGroupVos);
    }, executor);

    //下面这个是和第一个infoFuture是并行的
    CompletableFuture<Void> imgFuture = CompletableFuture.runAsync(() -> {
      //2、sku的图片信息 pms_sku_info
      List<SkuImagesEntity> images = skuImagesService.getImagesBySkuId(skuId);
      skuItemVo.setImages(images);
    }, executor);

    //查询当前sku是否参与秒杀优惠
    CompletableFuture<Void> secKillFuture = CompletableFuture.runAsync(() -> {
      R r = seckillFeignService.getSkuSeckillInfo(skuId);
      if (r.getCode() == 0) {
        SeckillInfoVo seckillInfoVo = r.getData(new TypeReference<SeckillInfoVo>() {
        });
        skuItemVo.setSeckillInfo(seckillInfoVo);
      }
    }, executor);

    //等待所有任务都完成
    CompletableFuture
      .allOf(/*infoFuture,*//*←infoFuture这里不用放进去,因为其它完了它肯定早完了*/saleAttrFuture, descFuture, baseAttrFuture, imgFuture, secKillFuture)
      .get();

    return skuItemVo;
  }

}
